package com.ark.frigate.zookeeper.threads;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * spring 线程池
 *
 * @author zengweilong
 */
@EnableAsync
@Configuration
public class TaskThreadPool {

    @Bean("commonAsyncExecutor")
    public Executor commonAsyncExecutor() {
        String threadName = "commonAsyncExecutor";
        return initExecutor(threadName, TaskThreadPoolConfig.CORE_POOL_SIZE);
    }

    private Executor initExecutor(String threadName, Integer corePoolSize) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(TaskThreadPoolConfig.MAX_POOL_SIZE);
        executor.setQueueCapacity(TaskThreadPoolConfig.QUEUE_CAPACITY);
        executor.setThreadNamePrefix(threadName + "-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setKeepAliveSeconds(60);
        executor.initialize();
        return executor;
    }
}
